package com.bourne.interceptor;

import com.alibaba.nacos.common.utils.HttpMethod;
import com.bourne.constant.StringConstant;
import com.bourne.enums.BizCodeEnum;
import com.bourne.model.LoginUser;
import com.bourne.util.CommonUtil;
import com.bourne.util.InterceptorUtil;
import com.bourne.util.JsonData;
import com.bourne.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author bourne
 * @PROJECT_NAME:
 * @DATE: 2021/4/3 13:12
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (HttpMethod.OPTIONS.equals(request.getMethod())) {
            return true;
        }
        String accessToken = InterceptorUtil.getLoginToke(request);
        if (StringUtils.isBlank(accessToken)) {
            log.warn("未获取到token信息");
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UN_LOGIN));
            return false;
        }

        Claims claims = JwtUtil.checkJWT(accessToken, response);
        if (claims == null){
            log.warn("token解析失败");
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UN_LOGIN));
            return false;
        }

        long userId = Long.parseLong(claims.get("id").toString());
        String headImg = (String) claims.get("head_img");
        String phone = (String) claims.get("phone");
        String name = (String) claims.get("name");
        LoginUser user = LoginUser.builder().headImg(headImg).name(name).id(userId).phone(phone).build();
        threadLocal.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}
